<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use app\admin\model\Cate;
use think\Db;

/**
 * 通用化API接口数据输出
 * @param int       $status     业务状态码
 * @param string    $message    信息提示
 * @param []        $data       数据
 * @param int       $httpCode   http状态码
 * @return array
 */
function jsonShow($status, $message, $data=[], $httpCode = 200) {
    $data = [
        'status' => $status,
        'message' => $message,
        'data' => $data,
    ];
    return  json($data, $httpCode);
}

//function return_json($code, $msg, $res, $exd1='', $exd2=0)
function return_json($code, $msg, $res, $exd=[])
{
    $data['code'] = $code;
    $data['msg'] = $msg;
    if($res !="" ){
        $data['data'] = $res;
    }
    //$data['exd1'] = $exd1;
    //$data['exd2'] = $exd2;
    $data['exd'] = $exd;
    return json_encode($data, JSON_UNESCAPED_UNICODE);
}

function setLog($logname,$data){

    $log_parh =  Env::get('root_path').'public/log/' .$logname . '/';

    $file_name = date('Ym') . ".log";
    if(is_array($data)){
        $text='【result】='.var_export($data,true).';';
    }else{
        $text = '【 动作 】：'.$data;
    }
    if(!is_dir($log_parh)){
        $flag = mkdir($log_parh,0777,true);
    }

    $contents = '['.date('Y-m-d H:i:s',time()).']'.'---'.PHP_EOL.$text;
    file_put_contents($log_parh.$file_name,$contents.PHP_EOL, FILE_APPEND);
    return;
}

function array_sort($array,$keys,$type='asc'){
    //$array为要排序的数组,$keys为要用来排序的键名,$type默认为升序排序
    $keysvalue = $new_array = array();
    foreach ($array as $k=>$v){
        $keysvalue[$k] = $v[$keys];
    }
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k=>$v){
        $new_array[$k] = $array[$k];
    }
    return $new_array;
}


//根据子节点查询跟树结构
function cate_tree_by_cid(&$info,$cid){
    if($info['parent_id'] == 0){
        $info['sub'] =  Cate::field('id,title,type,is_nav')->where('parent_id',$info['id'])->order('sort asc,id asc')->select();
        foreach ($info['sub'] as $key1 => $val1) {
			$arr = Cate::field('id,title,type,is_nav')->where('parent_id',$val1['id'])->order('sort asc,id asc')->select();
            $info['sub'][$key1]['sub'] = $arr??[];

        }
    }else{
        $info = Cate::where('id',$info['parent_id'])->find();
        cate_tree_by_cid($info,$info['id']);
    }
    //
    if(is_array($info)){
        $info['level'] = arrayLevel($info);
    }else{
        $info['level'] = arrayLevel($info->toArray());
    }

    //dump($info);
    return $info;
}

//判断数组为几维数组
function arrayLevel($arr){
    $al = array(0);
    aLs($arr,$al);
    return max($al);
}
function aLs($arr,&$al,$level=0){
    if(is_array($arr) && !empty($arr)){
        $level++;
        $al[] = $level;
        foreach($arr as $v){
            aLs($v,$al,$level);
        }
    }
}

function array_page($array,$start,$page=200){
    $new_array = [];
    foreach ($array as $k=>$v){
        if($k>=$start && $k<$start+$page){
            $new_array[$k] = $array[$k];
        }
    }
    return $new_array;
}

function ColorWhite(float $Alpha = 100)
{
    return new pChart\pColor(255,255,255,$Alpha);
}

function ColorBlack(float $Alpha = 100)
{
    return new pChart\pColor(0,0,0,$Alpha);
}

function isCheckMobile($value)
{
    $value = trim($value);
    $Regex = "/^1[3-9][0-9]\d{8}$/";
    if(preg_match($Regex,$value)) {
        return true;
    } else {
        return false;
    }
}

function isCheckEmail($email)
{
    $email = trim($email);
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

//获取所有子节点id
function getAllChildId($id,$data=[]){
    $pids = DB::name('cate')->where('parent_id',$id)->column('id');
    if(count($pids)>0){
        foreach($pids as $v){
            $data[] = $v;
            $data = getAllChildId($v,$data); //注意写$data 返回给上级
        }
    }
    if(count($data)>0){
        return $data;
    }else{
        return false;
    }
}

/**
 * 导入excel文件
 * @param  string $file excel文件路径
 * @return array        excel文件内容数组
 */
function import_excel($file){
    // 判断文件是什么格式
    $type = pathinfo($file);
    $type = strtolower($type["extension"]);
    $type=$type==='csv' ? $type : 'Excel2007'; //注意：xls:'Excel5'、xlsx:'Excel2007'

    //dump($_SERVER['DOCUMENT_ROOT']);die;
    ini_set('max_execution_time', '0');
    // 判断使用哪种格式
    $objReader = PHPExcel_IOFactory::createReader($type);
    $objPHPExcel = $objReader->load($_SERVER['DOCUMENT_ROOT'].$file);
    $sheet = $objPHPExcel->getSheet(0);
    // 取得总行数
    $highestRow = $sheet->getHighestRow();
    // 取得总列数
    $highestColumn = $sheet->getHighestColumn();
    //循环读取excel文件,读取一条,插入一条
    $data=array();
    //从第一行开始读取数据
    for($j=1;$j<=$highestRow;$j++){
        //从A列读取数据
        for($k='A';$k<=$highestColumn;$k++){
            // 读取单元格
            //$data[$j][]=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();

            $val = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
            if(is_object($val)){
                $val= $val->__toString();
            }
            $data[$j][]=$val;
        }
    }
    return $data;
}


function get_show_name($field){
    return DB::name('article_field')->where('field_name',$field)->value('show_name');
}
function get_is_show($field){
    return DB::name('article_field')->where('field_name',$field)->value('is_show');
}